package org.springblade.modules.admin.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lark.oapi.Client;
import com.lark.oapi.service.bitable.v1.model.*;
import lombok.AllArgsConstructor;
import org.springblade.common.config.FeiShuConfiguration;
import org.springblade.common.enums.FeiShuDocumentEnum;
import org.springblade.common.enums.FeishuClientEnum;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.feishu.*;
import org.springblade.modules.admin.entity.UserPerformanceMonth;
import org.springblade.modules.admin.enums.MaintainPlanContentEnum;
import org.springblade.modules.admin.enums.TaskStatusEnum;
import org.springblade.modules.admin.mapper.UserPerformanceMonthMapper;
import org.springblade.modules.admin.service.ElevatorService;
import org.springblade.modules.admin.service.IMaintainPlanContentService;
import org.springblade.modules.admin.service.UserPerformanceMonthService;
import org.springblade.modules.admin.service.feishu.IFeiShuDocumentService;
import org.springblade.modules.admin.vo.ElevatorEffectedVO;
import org.springblade.modules.system.service.IUserService;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@AllArgsConstructor
@Service
public class UserPerformanceMonthServiceImpl extends BaseServiceImpl<UserPerformanceMonthMapper, UserPerformanceMonth> implements UserPerformanceMonthService {

	private final IMaintainPlanContentService planContentService;
	private final IUserService userService;
	private final IFeiShuDocumentService feiShuDocumentService;
	private final ElevatorService elevatorService;
	private final Environment environment;
	private final FeiShuConfiguration feiShuConfiguration;
	private static final String TENANT_ID = "592800";

	@Override
	public void generateFeiShuUserPerformanceMonth(String lastMonth) {
		// 根据时间获取指定范围工单,工单关联所有用户,用户对应工单签到次数
		List<UserPerformanceMonthPlanListDTO> list = planContentService.listUserPerformancePlanList(lastMonth,TENANT_ID);
		if(Func.isNotEmpty(list)){
			list = list.stream().filter(e -> Func.isNotEmpty(e.getUserRoleAlias())
				&& (e.getUserRoleAlias().contains("maintenance")
				|| e.getUserRoleAlias().contains("expert")
				|| e.getUserRoleAlias().contains("repair"))).collect(Collectors.toList());
			Map<Long,List<UserPerformanceMonthPlanListDTO>> userGroup = list.stream().collect(Collectors.groupingBy(UserPerformanceMonthPlanListDTO::getUserId));
			Map<Long,List<UserPerformanceMonthPlanListDTO>> planGroup = list.stream().collect(Collectors.groupingBy(UserPerformanceMonthPlanListDTO::getPlanId));
			List<Long> userIds = list.stream().map(UserPerformanceMonthPlanListDTO::getUserId).distinct().collect(Collectors.toList());
			// 根据关联工单用户获取用户月绩效基础数据
			List<FeiShuUserPerformanceMonthDTO> resultList = userService.selectSimpleUserPerformanceMonthByIds(userIds);
			// 根据用户及时间获取对应责任梯 责任组的梯 责任梯工单 责任组的梯工单
			List<FeiShuUserDeptElevatorWxPlanDTO> userDeptElevatorWxPlanDTOS = planContentService.selectUserDeptElevatorWxPlan(lastMonth,userIds);
			// 数据存储对象
			List<UserPerformanceMonth> userPerformanceMonths = new ArrayList<>();
			resultList.forEach(e -> {
				// 获取对应用户工单数据
				List<UserPerformanceMonthPlanListDTO> userList = userGroup.get(e.getUserId());
				// 根据工单分组 保养 维修 事务
				List<UserPerformanceMonthPlanListDTO> userByList = userList.stream().filter(k -> MaintainPlanContentEnum.MAINTAIN_BY.getId() == k.getTypeStatus()).collect(Collectors.toList());
				List<UserPerformanceMonthPlanListDTO> userWxList = userList.stream().filter(k -> MaintainPlanContentEnum.MAINTAIN_WX.getId() == k.getTypeStatus()).collect(Collectors.toList());
				List<UserPerformanceMonthPlanListDTO> userSwList = userList.stream().filter(k -> MaintainPlanContentEnum.MAINTAIN_AFFAIR.getId() == k.getTypeStatus()).collect(Collectors.toList());
				// 根据条件处理封装绩效所需统计数据
				e.setByPlanTotal(userByList.stream().map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByActualFinishTotal(userByList.stream().filter(k -> TaskStatusEnum.BY_SIGN.getStatus() == k.getPlanStatus()
					&& k.getSignCount() > 0).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByActualFinishInVainTotal(userByList.stream().filter(k -> TaskStatusEnum.BY_SIGN.getStatus() == k.getPlanStatus()
					&& k.getSignCount() > 0 && 1 == k.getScoreStatus() && 2 == k.getScoreType()).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setBySoloTotal(userByList.stream().filter(k -> planGroup.get(k.getPlanId()).stream().map(UserPerformanceMonthPlanListDTO::getUserId).distinct().count() == 1).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByActualFinishSoloTotal(userByList.stream().filter(k -> planGroup.get(k.getPlanId()).stream().map(UserPerformanceMonthPlanListDTO::getUserId).distinct().count() == 1
					&& TaskStatusEnum.BY_SIGN.getStatus() == k.getPlanStatus()).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByActualFinishInVainSoloTotal(userByList.stream().filter(k -> planGroup.get(k.getPlanId()).stream().map(UserPerformanceMonthPlanListDTO::getUserId).distinct().count() == 1
					&& TaskStatusEnum.BY_SIGN.getStatus() == k.getPlanStatus() && 1 == k.getScoreStatus() && 2 == k.getScoreType()).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByMultiplayerTotal(userByList.stream().filter(k -> planGroup.get(k.getPlanId()).stream().map(UserPerformanceMonthPlanListDTO::getUserId).distinct().count() > 1)
					.map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByActualFinishMultiplayerTotal(userByList.stream().filter(k -> planGroup.get(k.getPlanId()).stream().map(UserPerformanceMonthPlanListDTO::getUserId).distinct().count() > 1
					&& TaskStatusEnum.BY_SIGN.getStatus() == k.getPlanStatus()).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByActualFinishInVainMultiplayerTotal(userByList.stream().filter(k -> planGroup.get(k.getPlanId()).stream().map(UserPerformanceMonthPlanListDTO::getUserId).distinct().count() > 1
					&& TaskStatusEnum.BY_SIGN.getStatus() == k.getPlanStatus() && 1 == k.getScoreStatus() && 2 == k.getScoreType()).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setBySoloNightTotal(userByList.stream().filter(k -> planGroup.get(k.getPlanId()).stream().map(UserPerformanceMonthPlanListDTO::getUserId).distinct().count() == 1
					&& k.getSignNightCount() > 0).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setBySoloNightInVainTotal(userByList.stream().filter(k -> planGroup.get(k.getPlanId()).stream().map(UserPerformanceMonthPlanListDTO::getUserId).distinct().count() == 1
					&& k.getSignNightCount() > 0 && 1 == k.getScoreStatus() && 2 == k.getScoreType()).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setBySoloNightEffectiveTotal(userByList.stream().filter(k -> planGroup.get(k.getPlanId()).stream().map(UserPerformanceMonthPlanListDTO::getUserId).distinct().count() == 1
					&& k.getSignNightCount() > 0 && 1 == k.getScoreStatus() && 1 == k.getScoreType()).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByMultiplayerNightTotal(userByList.stream().filter(k -> planGroup.get(k.getPlanId()).stream().map(UserPerformanceMonthPlanListDTO::getUserId).distinct().count() > 1
					&& k.getSignNightCount() > 0).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByMultiplayerNightInVainTotal(userByList.stream().filter(k -> planGroup.get(k.getPlanId()).stream().map(UserPerformanceMonthPlanListDTO::getUserId).distinct().count() > 1
					&& k.getSignNightCount() > 0 && 1 == k.getScoreStatus() && 2 == k.getScoreType()).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByMultiplayerNightEffectiveTotal(userByList.stream().filter(k -> planGroup.get(k.getPlanId()).stream().map(UserPerformanceMonthPlanListDTO::getUserId).distinct().count() > 1
					&& k.getSignNightCount() > 0 && 1 == k.getScoreStatus() && 1 == k.getScoreType()).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByTotal(userByList.stream().map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByFinishTotal(userByList.stream().filter(k -> TaskStatusEnum.BY_SIGN.getStatus() == k.getPlanStatus())
					.map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByScoredTotal(userByList.stream().filter(k -> 1 == k.getScoreStatus()).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByFlunkTotal(userByList.stream().filter(k -> 1 == k.getScoreStatus()
					&& k.getScore().compareTo(6.0) < 0).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByPassTotal(userByList.stream().filter(k -> 1 == k.getScoreStatus()
					&& k.getScore().compareTo(6.0) > -1
					&& k.getScore().compareTo(7.0) < 0).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByIntermediateTotal(userByList.stream().filter(k -> 1 == k.getScoreStatus()
					&& k.getScore().compareTo(7.0) > -1
					&& k.getScore().compareTo(8.0) < 0).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByGoodTotal(userByList.stream().filter(k -> 1 == k.getScoreStatus()
					&& k.getScore().compareTo(8.0) > -1
					&& k.getScore().compareTo(9.0) < 0).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByOutstandingTotal(userByList.stream().filter(k -> 1 == k.getScoreStatus()
					&& k.getScore().compareTo(9.0) > -1).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByPassOrAboveTotal(userByList.stream().filter(k -> 1 == k.getScoreStatus()
					&& k.getScore().compareTo(6.0) > -1).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				Map<Long,Double> userPlanScoreMap = userByList.stream().filter(k -> 1 == k.getScoreStatus()).collect(Collectors.toMap(UserPerformanceMonthPlanListDTO::getPlanId,UserPerformanceMonthPlanListDTO::getScore));
				if(Func.isNotEmpty(userPlanScoreMap)){
					e.setByScoreSum(userPlanScoreMap.values().stream().mapToDouble(k -> k).sum());
				}
				if(e.getByScoredTotal() > 0){
					e.setByScoreAve(BigDecimal.valueOf(e.getByScoreSum()).divide(BigDecimal.valueOf(e.getByScoredTotal()),2, RoundingMode.HALF_UP).doubleValue());
				}
				e.setSwTotal(userSwList.stream().map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
//				e.setByOverdueOneDayTotal(userByList.stream().filter(k -> TaskStatusEnum.BY_SIGN.getStatus() == k.getPlanStatus()
//					&& 2 == k.getAuditType()
//					&& k.getMaintainSignatureTime().getTime() == k.getOverdueDate().getTime()).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
//				e.setByOverdueMultiDayTotal(userByList.stream().filter(k -> TaskStatusEnum.BY_SIGN.getStatus() == k.getPlanStatus()
//					&& 2 == k.getAuditType()
//					&& k.getMaintainSignatureTime().getTime() > k.getOverdueDate().getTime()).map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByOverdueOneDayNotStartTotal(userByList.stream().filter(k -> 2 == k.getAuditType()
					&& ((Func.isEmpty(k.getMaintainSignatureTime()) && DateUtil.betweenDay(DateUtil.parseDate(DateUtil.today()),k.getOverdueDate(),Boolean.TRUE) == 1)
						|| (Func.isNotEmpty(k.getMaintainSignatureTime()) && DateUtil.parseDate(DateUtil.formatDate(k.getPlanBeginTime())).getTime() == k.getOverdueDate().getTime()))
					&& k.getPlanBeginTime().getTime() >= DateUtil.parse(DateUtil.formatDate(k.getOverdueDate()) + " 12","yyyy-MM-dd H").getTime())
					.map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setByOverdueOneDayNotFinishTotal(userByList.stream().filter(k -> 2 == k.getAuditType()
						&& ((Func.isEmpty(k.getMaintainSignatureTime()) && DateUtil.betweenDay(DateUtil.parseDate(DateUtil.today()),k.getOverdueDate(),Boolean.TRUE) == 1)
						|| (Func.isNotEmpty(k.getMaintainSignatureTime()) && k.getMaintainSignatureTime().getTime() == k.getOverdueDate().getTime()))
						&& Func.isNotEmpty(k.getPlanEndTime()) && k.getPlanEndTime().getTime() >= DateUtil.parse(DateUtil.formatDate(k.getOverdueDate()) + " 12","yyyy-MM-dd H").getTime())
					.map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setWxTotal(userWxList.stream().map(UserPerformanceMonthPlanListDTO::getPlanId).distinct().count());
				e.setUserElevatorTotal(userDeptElevatorWxPlanDTOS.stream().filter(k -> k.getUserId().equals(e.getUserId())
					&& 1 == k.getTemp()).map(FeiShuUserDeptElevatorWxPlanDTO::getElevatorId).distinct().count());
				e.setUserDeptElevatorTotal(userDeptElevatorWxPlanDTOS.stream().filter(k -> k.getUserId().equals(e.getUserId())
					&& 2 == k.getTemp()).map(FeiShuUserDeptElevatorWxPlanDTO::getElevatorId).distinct().count());
				e.setUserDeptElevatorWxTotal(userDeptElevatorWxPlanDTOS.stream().filter(k -> k.getUserId().equals(e.getUserId())
					&& 3 == k.getTemp()).map(FeiShuUserDeptElevatorWxPlanDTO::getPlanId).distinct().count());
				e.setUserElevatorWxTotal(userDeptElevatorWxPlanDTOS.stream().filter(k -> k.getUserId().equals(e.getUserId())
					&& 4 == k.getTemp()).map(FeiShuUserDeptElevatorWxPlanDTO::getPlanId).distinct().count());
				e.setUserElevatorWxClientTotal(userDeptElevatorWxPlanDTOS.stream().filter(k -> k.getUserId().equals(e.getUserId())
					&& 4 == k.getTemp() && (2 == k.getWorkOrderType() || (1 == k.getWorkOrderType() && "waiter".equals(k.getRoleAlias())))).map(FeiShuUserDeptElevatorWxPlanDTO::getPlanId).distinct().count());
				e.setUserElevatorWxInteriorTotal(userDeptElevatorWxPlanDTOS.stream().filter(k -> k.getUserId().equals(e.getUserId())
					&& 4 == k.getTemp() && 1 == k.getWorkOrderType() && !"waiter".equals(k.getRoleAlias())).map(FeiShuUserDeptElevatorWxPlanDTO::getPlanId).distinct().count());

				UserPerformanceMonth entity = new UserPerformanceMonth();
				entity.setUserId(e.getUserId());
				entity.setPerData(e);
				entity.setRecordDate(lastMonth);
				userPerformanceMonths.add(entity);
			});

			if(Func.isNotEmpty(userPerformanceMonths)){
				super.remove(Wrappers.<UserPerformanceMonth>lambdaQuery().eq(UserPerformanceMonth::getRecordDate,lastMonth)
					.in(UserPerformanceMonth::getUserId,userPerformanceMonths.stream().map(UserPerformanceMonth::getUserId).collect(Collectors.toList())));
				super.saveBatch(userPerformanceMonths);
			}

//			this.sendFeiShuUserPerformanceMonth(resultList,lastMonth);
			if(Func.isNotEmpty(resultList)){
				resultList = resultList.stream().sorted(Comparator.comparing(FeiShuUserPerformanceMonthDTO::getDeptNames).thenComparing(FeiShuUserPerformanceMonthDTO::getRoleNames)).collect(Collectors.toList());
			}

			//当前环境
			String curEnvironment = environment.getActiveProfiles()[0];
			if (Func.equalsSafe(curEnvironment, "prod")) {
				this.sendFeiShuUserPerformanceMonth(resultList,lastMonth);
			}
		}

	}

	@Override
	public void generateFeiShuElevatorMaintainCostMonth(String lastMonth) {
		Date lastMonthDate = DateUtil.parse(lastMonth,"yyyy-MM");
		List<ElevatorEffectedVO> elevatorEffectedList = planContentService.selectElevatorEffectedListByDate(DateUtil.beginOfMonth(lastMonthDate), DateUtil.endOfMonth(lastMonthDate));
		if(Func.isNotEmpty(elevatorEffectedList)){
			List<Long> elevatorIds = elevatorEffectedList.stream().map(ElevatorEffectedVO::getElevatorId).distinct().collect(Collectors.toList());
			List<ElevatorMaintainCostPlanListDTO> costPlanList = planContentService.selectElevatorMaintainCostPlanListMonth(TENANT_ID,lastMonth,elevatorIds);
			if(Func.isNotEmpty(costPlanList)){
				List<ElevatorMaintainCostListDTO> resultList = elevatorService.selectElevatorMaintainCostList(elevatorIds);
				resultList.forEach(e -> {
					e.setMonth(DateUtil.format(DateUtil.parse(lastMonth,"yyyy-MM"),"M月"));
					e.setBySoloTotal(costPlanList.stream().filter(k -> k.getElevatorId().equals(e.getElevatorId())
						&& k.getPlanUserCount() == 1
						&& MaintainPlanContentEnum.MAINTAIN_BY.getId() == k.getPlanTypeStatus()).map(ElevatorMaintainCostPlanListDTO::getPlanId).distinct().count());
					e.setByMultiplayerTotal(costPlanList.stream().filter(k -> k.getElevatorId().equals(e.getElevatorId())
						&& k.getPlanUserCount() > 1
						&& MaintainPlanContentEnum.MAINTAIN_BY.getId() == k.getPlanTypeStatus()).map(ElevatorMaintainCostPlanListDTO::getPlanId).distinct().count());
					e.setByTotal(costPlanList.stream().filter(k -> k.getElevatorId().equals(e.getElevatorId()) && MaintainPlanContentEnum.MAINTAIN_BY.getId() == k.getPlanTypeStatus())
						.map(ElevatorMaintainCostPlanListDTO::getPlanId).distinct().count());
					e.setWxTotal(costPlanList.stream().filter(k -> k.getElevatorId().equals(e.getElevatorId()) && MaintainPlanContentEnum.MAINTAIN_WX.getId() == k.getPlanTypeStatus())
						.map(ElevatorMaintainCostPlanListDTO::getPlanId).distinct().count());
					e.setSwTotal(costPlanList.stream().filter(k -> k.getElevatorId().equals(e.getElevatorId()) && MaintainPlanContentEnum.MAINTAIN_AFFAIR.getId() == k.getPlanTypeStatus())
						.map(ElevatorMaintainCostPlanListDTO::getPlanId).distinct().count());
				});
//			this.sendFeiShuElevatorMaintainCostMonth(resultList);
				//当前环境
				String curEnvironment = environment.getActiveProfiles()[0];
//				if (Func.equalsSafe(curEnvironment, "dev")) {
				if (Func.equalsSafe(curEnvironment, "prod")) {
					// 正式环境
					this.sendFeiShuElevatorMaintainCostMonth(resultList,lastMonth);
				}
			}
		}

	}

	@Override
	public void generateFeiShuElevatorPlanMonth(String lastMonth) {

		List<ElevatorMaintainCostPlanListDTO> costPlanList = planContentService.selectElevatorMaintainCostPlanListMonth(TENANT_ID,lastMonth, null);
		if(Func.isNotEmpty(costPlanList)){
			List<Long> elevatorIds = costPlanList.stream().map(ElevatorMaintainCostPlanListDTO::getElevatorId).distinct().collect(Collectors.toList());
			List<ElevatorMaintainCostListDTO> elevatorList = elevatorService.selectElevatorMaintainCostList(elevatorIds);
			List<ElevatorMaintainCostListDTO> resultList = new ArrayList<>();
			costPlanList.forEach(e -> {
				ElevatorMaintainCostListDTO elevator = elevatorList.stream().filter(k -> k.getElevatorId().equals(e.getElevatorId())).findFirst().orElse(new ElevatorMaintainCostListDTO());
				ElevatorMaintainCostListDTO result = new ElevatorMaintainCostListDTO();
				result.setBuildingName(elevator.getBuildingName());
				result.setBuildingCityName(elevator.getBuildingCityName());
				result.setBuildingAddress(elevator.getBuildingAddress());
				result.setElevatorAddress(elevator.getElevatorAddress());
				result.setElevatorBrandName(elevator.getElevatorBrandName());
				result.setElevatorCreateTime(elevator.getElevatorCreateTime());
				result.setElevatorRegisterNumber(elevator.getElevatorRegisterNumber());
				result.setElevatorDriveMode(elevator.getElevatorDriveMode());
				result.setMonth(DateUtil.format(DateUtil.parse(lastMonth,"yyyy-MM"),"M月"));
				result.setPlanDate(e.getPlanDate());
				result.setPlanTypeStatus(e.getPlanTypeStatus());
				result.setPlanStatus(e.getPlanStatus());
				if(MaintainPlanContentEnum.MAINTAIN_WX.getId() == e.getPlanTypeStatus()){
					result.setPlanDate(e.getPlanEndTime());
					result.setPlanWorkOrderType(e.getWorkOrderType() == 1 ? "内部整改" : "客户报障");
				}
				if(MaintainPlanContentEnum.MAINTAIN_BY.getId() == e.getPlanTypeStatus()){
					result.setUserNum(e.getPlanUserCount() > 1 ? "双人" : "单人");
				}
				result.setPlanUserNames(e.getPlanUserNames());
				resultList.add(result);
			});
//			List<ElevatorMaintainCostListDTO> byResultList = resultList.stream().filter(e -> MaintainPlanContentEnum.MAINTAIN_BY.getId() == e.getPlanTypeStatus()).collect(Collectors.toList());
//			if(Func.isNotEmpty(byResultList)){
//				this.sendFeiShuElevatorPlanMonth(byResultList,MaintainPlanContentEnum.MAINTAIN_BY.getId());
//			}
//			List<ElevatorMaintainCostListDTO> wxResultList = resultList.stream().filter(e -> MaintainPlanContentEnum.MAINTAIN_WX.getId() == e.getPlanTypeStatus()).collect(Collectors.toList());
//			if(Func.isNotEmpty(byResultList)){
//				this.sendFeiShuElevatorPlanMonth(wxResultList,MaintainPlanContentEnum.MAINTAIN_WX.getId());
//			}
//			List<ElevatorMaintainCostListDTO> swResultList = resultList.stream().filter(e -> MaintainPlanContentEnum.MAINTAIN_AFFAIR.getId() == e.getPlanTypeStatus()).collect(Collectors.toList());
//			if(Func.isNotEmpty(byResultList)){
//				this.sendFeiShuElevatorPlanMonth(swResultList,MaintainPlanContentEnum.MAINTAIN_AFFAIR.getId());
//			}
			//当前环境
			String curEnvironment = environment.getActiveProfiles()[0];
//			if (Func.equalsSafe(curEnvironment, "dev")) {
			if (Func.equalsSafe(curEnvironment, "prod")) {
				// 正式环境
				List<ElevatorMaintainCostListDTO> byResultList = resultList.stream().filter(e -> MaintainPlanContentEnum.MAINTAIN_BY.getId() == e.getPlanTypeStatus()).collect(Collectors.toList());
				if(Func.isNotEmpty(byResultList)){
					this.sendFeiShuElevatorPlanMonth(byResultList,MaintainPlanContentEnum.MAINTAIN_BY.getId(),lastMonth);
				}
				List<ElevatorMaintainCostListDTO> wxResultList = resultList.stream().filter(e -> MaintainPlanContentEnum.MAINTAIN_WX.getId() == e.getPlanTypeStatus()).collect(Collectors.toList());
				if(Func.isNotEmpty(byResultList)){
					this.sendFeiShuElevatorPlanMonth(wxResultList,MaintainPlanContentEnum.MAINTAIN_WX.getId(), lastMonth);
				}
				List<ElevatorMaintainCostListDTO> swResultList = resultList.stream().filter(e -> MaintainPlanContentEnum.MAINTAIN_AFFAIR.getId() == e.getPlanTypeStatus()).collect(Collectors.toList());
				if(Func.isNotEmpty(byResultList)){
					this.sendFeiShuElevatorPlanMonth(swResultList,MaintainPlanContentEnum.MAINTAIN_AFFAIR.getId(), lastMonth);
				}
			}
		}
	}

	private void sendFeiShuElevatorPlanMonth(List<ElevatorMaintainCostListDTO> resultList, Integer planTypeStatus, String lastMonth) {
		// 1. 数据准备：appToken，tableId，要对比新增的数据
		String appToken;
		String tableId;
		String viewId;
		if(MaintainPlanContentEnum.MAINTAIN_BY.getId() == planTypeStatus){
			appToken = FeiShuDocumentEnum.ELEVATOR_BY_MONTH.getAppToken();
			tableId = FeiShuDocumentEnum.ELEVATOR_BY_MONTH.getTableId();
			viewId = "vewTVdtadS";
		}else if(MaintainPlanContentEnum.MAINTAIN_WX.getId() == planTypeStatus){
			appToken = FeiShuDocumentEnum.ELEVATOR_WX_MONTH.getAppToken();
			tableId = FeiShuDocumentEnum.ELEVATOR_WX_MONTH.getTableId();
			viewId = "vewSlQoA7J";
		}else {
			appToken = FeiShuDocumentEnum.ELEVATOR_SW_MONTH.getAppToken();
			tableId = FeiShuDocumentEnum.ELEVATOR_SW_MONTH.getTableId();
			viewId = "vewDPvNhs3";
		}

		// 2. 数据处理、数据封装
		FeiShuBatchDTO batchDTO = new FeiShuBatchDTO();
		List<FeiShuFieldsDTO> records = new ArrayList<>();
		for (ElevatorMaintainCostListDTO t : resultList) {

			FeiShuFieldsDTO element = new FeiShuFieldsDTO();
			Map<String, Object> elementMap = new HashMap<>(30);

			elementMap.put("项目名称", t.getBuildingName());
			elementMap.put("所在城市", t.getBuildingCityName());
			elementMap.put("详细地址", t.getBuildingAddress());
			elementMap.put("电梯名称", t.getElevatorAddress());
			elementMap.put("单位内编号", t.getElevatorRegisterNumber());
			elementMap.put("电梯类型", t.getElevatorDriveMode());
			elementMap.put("电梯品牌", t.getElevatorBrandName());
			elementMap.put("开始服务时间", t.getElevatorCreateTime().getTime());
//			elementMap.put("月份", t.getMonth());
			if(MaintainPlanContentEnum.MAINTAIN_BY.getId() == planTypeStatus){
				elementMap.put("保养工单日期",t.getPlanDate().getTime());
				elementMap.put("保养人数",t.getUserNum());
				elementMap.put("保养人员",t.getPlanUserNames());
			}
			if(MaintainPlanContentEnum.MAINTAIN_WX.getId() == planTypeStatus){
				elementMap.put("维修工单日期",t.getPlanDate().getTime());
				elementMap.put("任务类型",t.getPlanWorkOrderType());
				elementMap.put("是否关闭",t.getPlanStatus().equals(TaskStatusEnum.WX_SIGN_FINISH.getStatus()) ? "是" : "否");
				elementMap.put("维修人员",t.getPlanUserNames());
			}
			if(MaintainPlanContentEnum.MAINTAIN_AFFAIR.getId() == planTypeStatus){
				elementMap.put("事务工单日期",t.getPlanDate().getTime());
				elementMap.put("事务执行人员",t.getPlanUserNames());
			}

			element.setFields(elementMap);
			records.add(element);
		}
		batchDTO.setRecords(records);
		List<JSONObject> deleteObjects = feiShuDocumentService.commandQueryBatch(appToken, tableId, null);
		// 遍历并获取 jsonObjects 的 封装成 FeiShuBatchDTO 对象
		List<String> r = new ArrayList<>();
		deleteObjects.forEach(j -> r.add(j.getString("record_id")));
		FeiShuBatchDTO deleteFeiShuBatchDTO = new FeiShuBatchDTO();
		deleteFeiShuBatchDTO.setRecords(r);
		// 直接覆盖
		feiShuDocumentService.commandDeleteBatchLimit(appToken, tableId, deleteFeiShuBatchDTO);
		// 构建client
		Client client = feiShuConfiguration.getClient(FeishuClientEnum.TABLE);
		// 创建请求对象
		PatchAppTableViewReq req = PatchAppTableViewReq.newBuilder()
			.appToken(appToken)
			.tableId(tableId)
			.viewId(viewId)
			.patchAppTableViewReqBody(PatchAppTableViewReqBody.newBuilder()
				.viewName(DateUtil.format(DateUtil.parse(lastMonth,"yyyy-MM"),"M月份"))
				.build())
			.build();

		// 发起请求
		try {
			PatchAppTableViewResp resp = client.bitable().appTableView().patch(req);
		}catch (Exception ignored){

		}
		// 3. 调用飞书API更新数据表、发送消息通知
		// 新增
		String result = feiShuDocumentService.commandAddBatchLimit(appToken, tableId, batchDTO);
		String message = "定时器或人工触发更新"+FeiShuDocumentEnum.getDescription(appToken,tableId)+"结果：" + result;
		feiShuDocumentService.commandSendGroupMessage(appToken, tableId, message);
	}

	private void sendFeiShuElevatorMaintainCostMonth(List<ElevatorMaintainCostListDTO> resultList, String lastMonth) {
		// 1. 数据准备：appToken，tableId，要对比新增的数据
		String appToken = FeiShuDocumentEnum.ELEVATOR_MAINTAIN_COST_MONTH.getAppToken();
		String tableId = FeiShuDocumentEnum.ELEVATOR_MAINTAIN_COST_MONTH.getTableId();

		// 2. 数据处理、数据封装
		FeiShuBatchDTO batchDTO = new FeiShuBatchDTO();
		List<FeiShuFieldsDTO> records = new ArrayList<>();
		for (ElevatorMaintainCostListDTO t : resultList) {

			FeiShuFieldsDTO element = new FeiShuFieldsDTO();
			Map<String, Object> elementMap = new HashMap<>(30);

			elementMap.put("项目名称", t.getBuildingName());
			elementMap.put("所在城市", t.getBuildingCityName());
			elementMap.put("详细地址", t.getBuildingAddress());
			elementMap.put("电梯名称", t.getElevatorAddress());
			elementMap.put("单位内编号", t.getElevatorRegisterNumber());
			elementMap.put("电梯类型", t.getElevatorDriveMode());
			elementMap.put("电梯品牌", t.getElevatorBrandName());
			elementMap.put("开始服务时间", t.getElevatorCreateTime().getTime());
			elementMap.put("月份", t.getMonth());
			elementMap.put("单人保养工单总数", t.getBySoloTotal());
			elementMap.put("双人保养工单总数", t.getByMultiplayerTotal());
			elementMap.put("保养工单(总数)", t.getByTotal());
			elementMap.put("维修工单(总数)", t.getWxTotal());
			elementMap.put("事务工单(总数)", t.getSwTotal());

			element.setFields(elementMap);
			records.add(element);
		}
		batchDTO.setRecords(records);
		List<JSONObject> deleteObjects = feiShuDocumentService.commandQueryBatch(appToken, tableId, null);
		// 遍历并获取 jsonObjects 的 封装成 FeiShuBatchDTO 对象
		List<String> r = new ArrayList<>();
		deleteObjects.forEach(j -> r.add(j.getString("record_id")));
		FeiShuBatchDTO deleteFeiShuBatchDTO = new FeiShuBatchDTO();
		deleteFeiShuBatchDTO.setRecords(r);
		// 直接覆盖
		feiShuDocumentService.commandDeleteBatchLimit(appToken, tableId, deleteFeiShuBatchDTO);
		// 构建client
		Client client = feiShuConfiguration.getClient(FeishuClientEnum.TABLE);
		// 创建请求对象
		PatchAppTableViewReq req = PatchAppTableViewReq.newBuilder()
			.appToken(appToken)
			.tableId(tableId)
			.viewId("vew5ep2uiw")
			.patchAppTableViewReqBody(PatchAppTableViewReqBody.newBuilder()
				.viewName(DateUtil.format(DateUtil.parse(lastMonth,"yyyy-MM"),"M月份"))
				.build())
			.build();

		// 发起请求
		try {
			PatchAppTableViewResp resp = client.bitable().appTableView().patch(req);
		}catch (Exception ignored){

		}
		// 3. 调用飞书API更新数据表、发送消息通知
		// 新增
		String result = feiShuDocumentService.commandAddBatchLimit(appToken, tableId, batchDTO);
		String message = "定时器或人工触发更新"+FeiShuDocumentEnum.getDescription(appToken,tableId)+"结果：" + result;
		feiShuDocumentService.commandSendGroupMessage(appToken, tableId, message);
	}

	private void sendFeiShuUserPerformanceMonth(List<FeiShuUserPerformanceMonthDTO> resultList, String lastMonth) {
		// 1. 数据准备：appToken，tableId，要对比新增的数据
		String appToken = FeiShuDocumentEnum.USER_PERFORMANCE_MONTH.getAppToken();
		String tableId = FeiShuDocumentEnum.USER_PERFORMANCE_MONTH.getTableId();

		// 2. 数据处理、数据封装
		FeiShuBatchDTO batchDTO = new FeiShuBatchDTO();
		List<FeiShuFieldsDTO> records = new ArrayList<>();
		for (FeiShuUserPerformanceMonthDTO t : resultList) {

			FeiShuFieldsDTO element = new FeiShuFieldsDTO();
			Map<String, Object> elementMap = new HashMap<>(30);

			elementMap.put("id", String.valueOf(t.getUserId()));
			elementMap.put("姓名", Func.toStrList(t.getRealName()));
			elementMap.put("岗位", Func.toStrList(t.getRoleNames()));
			elementMap.put("区域", Func.toStrList(t.getDeptNames()));
			elementMap.put("计划维保总工单数", t.getByPlanTotal());
			elementMap.put("实际完成维保总工单数", t.getByActualFinishTotal());
			elementMap.put("实际完成维保总工单数(无效)", t.getByActualFinishInVainTotal());
			elementMap.put("单人计划维保工单数", t.getBySoloTotal());
			elementMap.put("实际单人完成维保工单数", t.getByActualFinishSoloTotal());
			elementMap.put("实际单人完成维保工单数(无效)", t.getByActualFinishInVainSoloTotal());
			elementMap.put("双人计划维保工单数", t.getByMultiplayerTotal());
			elementMap.put("实际双人完成保养工单数", t.getByActualFinishMultiplayerTotal());
			elementMap.put("实际双人完成保养工单数(无效)", t.getByActualFinishInVainMultiplayerTotal());
			elementMap.put("单人夜间工单数", t.getBySoloNightTotal());
			elementMap.put("单人夜间工单数(无效)", t.getBySoloNightInVainTotal());
//			elementMap.put("单人夜间工单数(有效)", t.getBySoloNightEffectiveTotal());
			elementMap.put("双人夜间工单数", t.getByMultiplayerNightTotal());
			elementMap.put("双人夜间工单数(无效)", t.getByMultiplayerNightInVainTotal());
//			elementMap.put("双人夜间工单数(有效)", t.getByMultiplayerNightEffectiveTotal());
			elementMap.put("sum(temp.总工单数)", t.getByTotal());
			elementMap.put("sum(temp.完成工单数)", t.getByFinishTotal());
			elementMap.put("sum(temp.已评分工单数)", t.getByScoredTotal());
			elementMap.put("sum(temp.不及格工单数)", t.getByFlunkTotal());
			elementMap.put("sum(temp.及格工单数)", t.getByPassTotal());
			elementMap.put("sum(temp.中等工单数)", t.getByIntermediateTotal());
			elementMap.put("sum(temp.良好工单数)", t.getByGoodTotal());
			elementMap.put("sum(temp.优秀工单数)", t.getByOutstandingTotal());
			elementMap.put("sum(temp.保养及格以上工单数)", t.getByPassOrAboveTotal());
			elementMap.put("sum(temp.完成评分的所有工单总分)", t.getByScoreSum());
			elementMap.put("平均分", t.getByScoreAve());
			elementMap.put("年审事务单", t.getSwTotal());
//			elementMap.put("除别墅梯逾期1天完成工单数", t.getByOverdueOneDayTotal());
//			elementMap.put("除别墅梯逾期大于1天完成工单数", t.getByOverdueMultiDayTotal());
			elementMap.put("第15天：12点前仍未开始保养工单数", t.getByOverdueOneDayNotStartTotal());
			elementMap.put("第15天：12点前未完成保养工单数", t.getByOverdueOneDayNotFinishTotal());
			elementMap.put("该人员维修工单", t.getWxTotal());
			elementMap.put("保养员责任电梯数(个人名下)", t.getUserElevatorTotal());
			elementMap.put("维修员责任电梯数(区域数量)", t.getUserDeptElevatorTotal());
			elementMap.put("区组下梯台的全部维修工单数", t.getUserDeptElevatorWxTotal());
			elementMap.put("维保员责任维修工单数", t.getUserElevatorWxTotal());
			elementMap.put("客户报障维修工单", t.getUserElevatorWxClientTotal());
			elementMap.put("内部整改维修工单", t.getUserElevatorWxInteriorTotal());

			element.setFields(elementMap);
			records.add(element);
		}
		batchDTO.setRecords(records);
		List<JSONObject> deleteObjects = feiShuDocumentService.commandQueryBatch(appToken, tableId, null);
		// 遍历并获取 jsonObjects 的 封装成 FeiShuBatchDTO 对象
		List<String> r = new ArrayList<>();
		deleteObjects.forEach(j -> r.add(j.getString("record_id")));
		FeiShuBatchDTO deleteFeiShuBatchDTO = new FeiShuBatchDTO();
		deleteFeiShuBatchDTO.setRecords(r);
		// 直接覆盖
		feiShuDocumentService.commandDeleteBatchLimit(appToken, tableId, deleteFeiShuBatchDTO);
		// 构建client
		Client client = feiShuConfiguration.getClient(FeishuClientEnum.TABLE);
		// 创建请求对象
		PatchAppTableViewReq req = PatchAppTableViewReq.newBuilder()
			.appToken(appToken)
			.tableId(tableId)
			.viewId("vewyx5FSTM")
			.patchAppTableViewReqBody(PatchAppTableViewReqBody.newBuilder()
				.viewName(DateUtil.format(DateUtil.parse(lastMonth,"yyyy-MM"),"M月份"))
				.build())
			.build();

		// 发起请求
		try {
			PatchAppTableViewResp resp = client.bitable().appTableView().patch(req);
		}catch (Exception ignored){

		}
		// 3. 调用飞书API更新数据表、发送消息通知
		// 新增
		String result = feiShuDocumentService.commandAddBatchLimit(appToken, tableId, batchDTO);
		String message = "定时器或人工触发更新"+FeiShuDocumentEnum.getDescription(appToken,tableId)+"结果：" + result;
		feiShuDocumentService.commandSendGroupMessage(appToken, tableId, message);
	}

}

